package mysql

import (
	"context"
	"errors"
	"go.uber.org/zap"
	"golang-sgg-daijia/internal/model"
	"gorm.io/gorm"
)

type OrderProfitsharingDao interface {
	Create(ctx context.Context, orderProfitsharing *model.OrderProfitsharing) error
	FindByID(ctx context.Context, id int64) (*model.OrderProfitsharing, error)
	FindByOrderID(ctx context.Context, OrderID int64) (*model.OrderProfitsharing, error)
}

func NewOrderProfitsharingDao(
	r *MysqlClient,
) OrderProfitsharingDao {
	return &orderProfitsharingDao{
		MysqlClient: r,
	}
}

type orderProfitsharingDao struct {
	*MysqlClient
}

func (r *orderProfitsharingDao) Create(ctx context.Context, orderProfitsharing *model.OrderProfitsharing) error {
	if err := r.DB(ctx).Create(orderProfitsharing).Error; err != nil {
		r.logger.WithContext(ctx).Error("orderProfitsharingDao|Create", zap.Error(err))
		return err
	}
	return nil
}

func (r *orderProfitsharingDao) FindByID(ctx context.Context, id int64) (*model.OrderProfitsharing, error) {
	orderProfitsharing := &model.OrderProfitsharing{}
	if err := r.DB(ctx).Where("id = ?", id).First(orderProfitsharing).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("orderProfitsharingDao|GetByID", zap.Error(err))
		return nil, err
	}
	return orderProfitsharing, nil
}

func (r *orderProfitsharingDao) FindByOrderID(ctx context.Context, OrderID int64) (*model.OrderProfitsharing, error) {
	orderProfitsharing := &model.OrderProfitsharing{}
	if err := r.DB(ctx).Where("order_id = ?", OrderID).First(orderProfitsharing).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("orderProfitsharingDao|FindByOrderID", zap.Error(err))
		return nil, err
	}
	return orderProfitsharing, nil
}